﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace BaiduYun
{
    public partial class FormMain : Form
    {
        private string shortUrlColl = string.Empty;
        public FormMain()
        {
            InitializeComponent();
        }

        private void btn_begin_Click(object sender, EventArgs e)
        {
            #region 初始化

            // 设置按钮状态
            btn_beginSearchGroup.Enabled = nud.Enabled = false;
            // 清空listview.items
            listView_showGroupUrl.Items.Clear();
            // 清空全局shortUrlColl
            shortUrlColl = string.Empty;

            int runNum = 0;
            // 声明委托
            Action<ProgressBar, int> SetProValue = (pro, value) => { pro.Value = value; };
            Action<ProgressBar, int> SetProMaxValue = (pro, value) => { pro.Maximum = value; };
            Action<ProgressBar> SetProIncrement = (pro) => { try { pro.Value++; } catch (Exception) { } };
            // 读取搜索深度
            int page = Convert.ToInt32(nud.Value);

            #endregion 初始化

            Task.Factory.StartNew(() =>
            {
                // 加入统计
                //Statistics.AddStatistics();
                var getTiebaTimesRes = BaiduYunGroup.GetTiebaTimes(page);
                int tiebaTimesNum = getTiebaTimesRes.Count();
                this.Invoke(SetProValue, progressBar1, 0); this.Invoke(SetProValue, progressBar2, 0);//初始化
                this.Invoke(SetProMaxValue, progressBar1, tiebaTimesNum);// 设置贴吧进度条最大值

                foreach (var tiebaTimesPair in getTiebaTimesRes)// 遍历贴吧
                {
                    this.Invoke(SetProIncrement, progressBar1);
                    var getPostUrlRes = BaiduYunGroup.GetTiebaUrl(tiebaTimesPair.Key);
                    int postUrlNum = getPostUrlRes.Count();
                    this.Invoke(SetProValue, progressBar2, 0);
                    this.Invoke(SetProMaxValue, progressBar2, postUrlNum);
                    foreach (var postUrl in getPostUrlRes) //遍历帖子
                    {
                        while (true)
                        {
                            if (Interlocked.Exchange(ref runNum, runNum) < 6)
                            {
                                Interlocked.Increment(ref runNum);
                                this.Invoke(SetProIncrement, progressBar2);
                                break;
                            }

                            Thread.Sleep(1000);
                        }
                        Task.Factory.StartNew(() =>
                        {
                            foreach (var shortUrl in BaiduYunGroup.GetTiebaShort(postUrl)) //遍历ShortUrl
                            {
                                var shortInfo = BaiduYunGroup.IsShortUse(shortUrl);
                                if (shortInfo != null) this.Invoke(new Action(() =>
                                {
                                    if (shortUrlColl.IndexOf(shortUrl) == -1)
                                    {
                                        shortUrlColl += shortUrl + "|";
                                        ListViewItem item = new ListViewItem();
                                        // ID
                                        item.Text = ((listView_showGroupUrl.Items.Count + 1).ToString());
                                        // 名称
                                        item.SubItems.Add(shortInfo.Value.name);
                                        // 人数
                                        item.SubItems.Add(shortInfo.Value.usercount);
                                        // 链接
                                        item.SubItems.Add(shortInfo.Value.shortUrl);
                                        lock (listView_showGroupUrl)
                                        {
                                            listView_showGroupUrl.Items.Add(item);
                                        }
                                    }
                                    else
                                    {
                                        return;
                                    }
                                }));
                            }
                            Interlocked.Decrement(ref runNum);
                        });
                    }
                }

                this.Invoke(new Action(() => { btn_beginSearchGroup.Enabled = nud.Enabled = true; }));
            });
        }

        private void btn_joinGroup_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("http://shang.qq.com/wpa/qunwpa?idkey=fcbe058b21478881eb091b278c7b724a4c63e0a6b9bc4b2949f7170bff900afa");
        }

        private void FormMain_Load(object sender, EventArgs e)
        {
            string ver = "1.4.5";
            this.Text = $"百度云分享链接搜寻 V{ver}";
        }

        private void listView_showGroupUrl_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            ListViewHitTestInfo info = listView_showGroupUrl.HitTest(e.X, e.Y);
            string shortUrl = info.Item.SubItems[3].Text;
            System.Diagnostics.Process.Start("http://pan.baidu.com/mbox/homepage?short=" + shortUrl);
        }

        private void listView_showGroupUrl_ItemChecked(object sender, ItemCheckedEventArgs e)
        {
        }

        private void listView_showGroupUrl_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
        }

        private void listView_showGroupUrl_ItemActivate(object sender, EventArgs e)
        {
        }

        private void btn_beginDeleteShield_Click(object sender, EventArgs e)
        {
            MessageBox.Show("功能未完成，敬请期待");
            return;
            #region 判断Cookie 是否有效

            string cookie = txt_cookie.Text;
            cookie = "BAIDUID=FBDA4A7839B977119EF51DC4275DA98E:FG=1; BIDUPSID=FBDA4A7839B977119EF51DC4275DA98E; PSTM=1459069264; PANWEB=1; bdshare_firstime=1459343148326; MCITY=-161%3A; BDUSS=hUajdoM1ZnRXJMNzBYdFBuUTBvWWhuQ0pSc2lLV0RiZ0lYSE9obnc4aDVjRGxYQVFBQUFBJCQAAAAAAAAAAAEAAADaa7w20fS54rXEd3JnMTIzAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHnjEVd54xFXMz; recommendTime=android2016-04-19%2018%3A38; Hm_lvt_adf736c22cd6bcc36a1d27e5af30949e=1460278454,1460785069,1461235384,1461323881; BDCLND=I8WjWoXuwn0IzN6dJtACs9NpItsh2nkz3zQE32SRvgo%3D; H_PS_PSSID=18881_1993_19684_1461_19671_18240_19781_17948_19803_19806_19807_17001_15524_11520_19811; TOPMSG=1461460718-0; STOKEN=8e186a9e67cb555520e668361544f74b1e7cb8675ffce1736b9e1e40d2d44f82; SCRC=fc02684964b3d17b60651b004893c8d7; Hm_lvt_7a3960b6f067eb0085b7f96ff5e660b0=1461459756,1461459969,1461460084,1461460668; Hm_lpvt_7a3960b6f067eb0085b7f96ff5e660b0=1461460699; PANPSC=2988938361828083291%3aprhVfOyoCTyR1tTMeU4gvez3uZlqClya3E8OlgHo7X9Mi%2fQTc97dbSeohW%2bUtmAWLJ94Z2KoTNAQbd2LJiZz7zyDU9xFytyIkEs1rJo29AGuyCc0v4thy1fUDd9arCIipVvFdWv64D2x9tiL1HMEjCaIcdkR9RO3GwfgGLF5emW7dF4ZXz6remtyQx%2f8DAIzBpfwYIqZVWh3MYyx6aD0yQ%3d%3d; cflag=15%3A3";
            bool isCookieValid = BaiduYunPan.IsCookieValid(cookie);
            if (!isCookieValid)
            {
                MessageBox.Show("Cookie无效");
                return;
            }

            #endregion 判断Cookie 是否有效

            BaiduYunPan b = new BaiduYunPan(cookie);
            Task.Factory.StartNew(()=> 
            {
                int page = 1;
                while (true)
                {
                    var list = b.GetVideoPath(page++);
                    //Console.WriteLine(page);
                    if (list == null) return;
                    List<string> shieldPath = new List<string>();
                    foreach (var item in list)
                    {
                        BaiduYunPan.IsImgShield(item.url);
                        shieldPath.Add(item.path);
                    }
                    b.DeleteFile(shieldPath.ToArray());
                }
                
            });

        }
    }
}